"""empty message

Revision ID: 4b4823a384e7
Revises: 55fe25bdf42b
Create Date: 2022-12-18 23:01:04.874862

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy import orm
from app import db

DeclarativeBase = orm.declarative_base()


class Expense(DeclarativeBase):
    __tablename__ = 'expense'
    id = sa.Column(sa.Integer, primary_key=True)
    date = sa.Column(sa.DateTime)
    created_at = sa.Column(sa.DateTime, nullable=False)


# revision identifiers, used by Alembic.
revision = '4b4823a384e7'
down_revision = '55fe25bdf42b'
branch_labels = None
depends_on = None


def upgrade():
    with op.batch_alter_table('expense', schema=None) as batch_op:
        batch_op.add_column(sa.Column('date', sa.DateTime()))

    # Data migration
    bind = op.get_bind()
    session = orm.Session(bind=bind)

    expenses = session.query(Expense).all()
    for expense in expenses:
        expense.date = expense.created_at

    try:
        session.bulk_save_objects(expenses)
        session.commit()
    except Exception as e:
        session.rollback()
        raise e

    with op.batch_alter_table('expense', schema=None) as batch_op:
        batch_op.alter_column('date', nullable=False)

    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    with op.batch_alter_table('expense', schema=None) as batch_op:
        batch_op.drop_column('date')

    # ### end Alembic commands ###
